package com.loopy.tomcat;

import com.loopy.tomcat.handler.RequestHandler;
import com.loopy.tomcat.servlet.loopyhttpSevlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class TomcatV03 {
    public static final ConcurrentHashMap<String, loopyhttpSevlet>
            servletMapping=new ConcurrentHashMap<>();
    public static final ConcurrentHashMap<String, String>
            servletUrlMapping=new ConcurrentHashMap<>();
    public void init()  {
        String path = TomcatV03.class.getResource("/").getPath();
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(path + "web.xml"));
            Element rootElement = document.getRootElement();
            List<Element> elements = rootElement.elements();
            for (Element element : elements) {
                if("servlet".equalsIgnoreCase(element.getName())){
                    Element servletName = element.element("servlet-name");
                    Element servletClass = element.element("servlet-class");
                    servletMapping.put(servletName.getText(),
                            (loopyhttpSevlet) Class.forName(servletClass.getText().trim()).newInstance());
//                System.out.println("发现servlet节点");
                } else if ("servlet-mapping".equalsIgnoreCase(element.getName())) {
                    Element servletName = element.element("servlet-name");
                    Element urlPattern = element.element("url-pattern");
                    servletUrlMapping.put(urlPattern.getText(),servletName.getText());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//      System.out.println(document);

        System.out.println("servletMapping="+servletMapping);
        System.out.println("servletUrlMapping="+servletUrlMapping);
    }
    public void run()  {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            System.out.println("=====hsptomcatv3在8080监听======");
            while (!serverSocket.isClosed()) {
                Socket socket = serverSocket.accept();
                RequestHandler hspRequestHandler =
                        new RequestHandler(socket);
                new Thread(hspRequestHandler).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)  {

        TomcatV03 tomcatV03 = new TomcatV03();
        tomcatV03.init();
        tomcatV03.run();
    }
}
